<?php
	
	session_start();
	
	// check for login
	if(!isset($_SESSION['atbat']) && !isset($_COOKIE['remember_atbat'])) {
	
		// no login, move to index page
		header("Location: http://localhost/atbat/html/");
	
	}
	
	// connect to db
	require_once '../db/db.php';
	
	// get user id
	$sql = "SELECT user_id FROM users WHERE MD5(username) IN ('";
	$sql .= ((isset($_SESSION['atbat'])) ? $_SESSION['atbat'] : '') . "', '";
	$sql .= ((isset($_COOKIE['remember_atbat'])) ? $_COOKIE['remember_atbat'] : '') . "')";
		
	$id = $db->query($sql)->fetchAll();
	$user_id = $id[0]['user_id'];
	
	// check for team id in URL
	if(!isset($_GET['id'])) {
		
		$message[] = '<p class="error">Team ID not set.</p>';
		$error = true;
		
	}else{
		
		$sql = "SELECT city, name, division, league, logo, url FROM teams WHERE team_id = " . $_GET['id'];
		$info = $db->query($sql)->fetchAll();
		$team = $info[0];
				
	}
	
	// process either incoming ajax request or local request
	if(isset($_POST['editTeam'])) {
	
		$error = false;
		
		// sanitize and validate data
		if(isset($_POST['team_id']) && $_POST['team_id'] != '') {
			
			if(filter_var($_POST['team_id'], FILTER_VALIDATE_INT)) {
				
				$id = filter_var($_POST['team_id'], FILTER_SANITIZE_NUMBER_INT);
				
			}else{
				
				$message[] = '<p class="error">Team ID is set incorrectly.</p>';
				$error = true;
				
			}
			
		}
		
		if(isset($_POST['team_city']) && $_POST['team_city'] != '') {
		
			$city = filter_var($_POST['team_city'], FILTER_SANITIZE_STRING);
		
		}else{
		
			$message[] = '<p class="error">Please give a city for your team.</p>';
			$error = true;
		
		}
		
		if(isset($_POST['team_name']) && $_POST['team_name'] != '') {
		
			$name = filter_var($_POST['team_name'], FILTER_SANITIZE_STRING);
			
		}else{
		
			$mesage[] = '<p class="error">Please name your team.</p>';
			$error = true;
		
		}
		
		if(isset($_POST['division']) && $_POST['division'] != '') {
		
			$division = filter_var($_POST['division'], FILTER_SANITIZE_STRING);
			
		}else{
		
			$message[] = '<p class="error">Please choose a division.</p>';
			$error = true;
		
		}
		
		if(isset($_POST['league']) && $_POST['league'] != '') {
		
			$league = filter_var($_POST['league'], FILTER_SANITIZE_STRING);
			
		}else{
		
			$message[] = '<p class="error">Please choose a league for your team.</p>';
			$error = true;
		
		}
		
		if(isset($_POST['url']) && $_POST['url'] != '') {
			
			if(filter_var($_POST['url'], FILTER_VALIDATE_URL)) {
			
				$url = filter_var($_POST['url'], FILTER_SANITIZE_URL);
				
			}else{
				
				$message[] = '<p class="notice">Please format your URL like so: http://www.example.com</p>';
				$error = true;
			
			}
			
		}else{ // no url given
		
			$url = '';
		
		}
		
		// handle logo upload if no other form errors
		if(isset($_FILES['team_logo']) && $error == false) {
		
			$uploaddir = 'team_images/';
			$uploadfile = $uploaddir . $user_id . '_' . basename($_FILES['team_logo']['name']);
						
			// check for correct file type
			if(($_FILES['team_logo']['type'] == "image/gif") || ($_FILES['team_logo']['type'] == "image/jpg") || ($_FILES['team_logo']['type'] == "image/jpeg") || ($_FILES['team_logo']['type'] == "image/pjpeg") || ($_FILES['team_logo']['type'] == "image/bmp")) {
			
				// check upload status
				switch($_FILES['team_logo']['error']) {
				
					case 0: // no error, upload successful
					
						if(file_exists($uploadfile)) { // check for dup files
						
							$message[] = '<p class="error">File already exists, please upload a different one.</p>';
							$error = true;
						
						}else{
						
							move_uploaded_file($_FILES['team_logo']['tmp_name'], $uploadfile);
							$logo = basename($_FILES['team_logo']['name']);	
							$message[] = '<p class="success">Logo uploaded successfully.</p>';
							
						}		
						break; 
						
					case 1: // exceeds php.ini file size
						$message[] = '<p class="error">File size too large. Please resize and upload again.</p>';
						$error = true;
						unset($uploadfile);
						break;
						
					case 2: // exceeds form file size
						$message[] = '<p class="error">File size too large. Please resize and upload again.</p>';
						$error = true;
						unset($uploadfile);
						break;
						
					case 3: // partial upload
						$message[] = '<p class="error">File only partially uploaded. Please try again.</p>';
						$error = true;
						unset($uploadfile);
						break;
						
					case 4: // no file uploaded
						$message[] = '<p class="error">No file uploaded.</p>';
						$error = true;
						unset($uploadfile);
						break;
						
					case 6: // missing temp folder
						$message[] = '<p class="error">Upload failed. Try again later.</p>';
						$message[] = '<p class="notice">Missing temp folder.</p>';
						$error = true;
						unset($uploadfile);
						break;
						
					case 7: // failed to write to disk
						$message[] = '<p class="error">Upload failed. Try again later.</p>';
						$message[] = '<p class="notice">Failed to write to disk.</p>';
						$error = true;
						unset($uploadfile);
						break;
						
					case 8: // extension caused failure
						$message[] = '<p class="error">Upload failed. Try again later.</p>';
						$message[] = '<p class="notice">Extension caused failure.</p>';
						$error = true;
						unset($uploadfile);
						break;
				
				}
				
			}else{ // incorrect type
			
				$message[] = '<p class="error">Incorrect file type, image must be a GIF, JPG or BMP.</p>';
				$error = true;
				unset($uploadfile);
			
			}
		
		}else{ // no logo
		
			$logo = '';
		
		}
		
		if($error == false) {
		
			$sql = "INSERT INTO teams (user_id, city, name, division, league, logo, url) VALUES ('";
			$sql .= $user_id . "', '" . $city . "', '" . $name . "', '" . $division . "', '";
			$sql .= $league . "', '" . $logo .  "', '" . $url . "')";
			// $message[] = '<p>' . $sql . '</p>';
			
			if($db->exec($sql) == 1) {
				
				// get id of new team
				$id = $db->lastInsertId();
				
				// show success message
				$message[] = '<p rel="' . $id . '" title="' . $city . ' ' . $name .'" class="success">Successfully created your team.</p>';
			
			}else{
			
				$message[] = '<p class="error">Could not create team.</p>';
				//$message[] = '<p class="notice">' . print_r($db->errorInfo()) . '</p>';
				$error = true;
			
			}
		
		}
		
		// check of this is a local or ajax request
		if($_POST['editTeam'] == 1) { // ajax
		
			foreach($message as $m) { $response .= $m; }
			
			exit($response);
		
		}
	
	}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <base href="http://localhost/atbat/html/" />
	<meta charset="utf-8">
	<title>AtBat :: Create a Team</title>
	<meta name="description" content="">
	<meta name="author" content="Sean Mullin, http://parametercontraption.com">
	<!--  Mobile Viewport Fix j.mp/mobileviewport & davidbcalhoun.com/2010/viewport-metatag -->
	<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
	<link rel="shortcut icon" href="images/design/favicon.ico">
	<link rel="apple-touch-icon" href="images/design/apple-touch-icon.png">
	<link rel="stylesheet" href="css/screen.css">
	<!-- For the less-enabled mobile browsers like Opera Mini --><script src="js/modernizr-1.5.min.js"></script>
</head>
<body>
	<?php require_once 'include/header.html'; ?>
    <section id="content">
    	<h1>Edit Your Team</h1>
        <p>Use the form below to edit your team.</p>
        <form method="post" action="edit-team" enctype="multipart/form-data">
        	<fieldset id="edit_team">
            	<legend>Team Details</legend>
                <?php if(isset($message)) foreach($message as $m) print $m; ?>
                <input type="hidden" name="team_id" id="team_id" value="<?php echo $_GET['id']; ?>" required />
                <p><label for="team_city">Team City:</label><input type="text" name="team_city" id="team_city" value="<?php echo $team['city']; ?>" required /></p>
                <p><label for="team_name">Team Name:</label><input type="text" name="team_name" id="team_name" value="<?php echo $team['name']; ?>" required /></p>
                <p>
                	<label for="division">Division:</label>
                	<select name="division" id="division" required>
                    	<?php
						
							$sql = "SHOW COLUMNS FROM teams LIKE 'division' ";
							$divs = $db->query($sql)->fetchAll();
							$div = $divs[0]['Type'];
														
							$regex = "/'(.*?)'/";
							preg_match_all($regex, $div, $enum_array);
							$enum_fields = $enum_array[1];
							
							foreach($enum_fields as $type) {
								
								if($type == $team['division']) {
									
									print '<option value="' . $team['division'] . '" selected>' . $team['division'] . '</option>';	
									
								}else{
									
									print '<option value="' . $type . '">' . $type . '</option>';
									
								}
							
							}
						
						?>
                    </select>    
                </p>
                <p>
                	<label for="league">League:</label>
                    <select name="league" id="league" required>
                    	<?php
						
							$sql = "SHOW COLUMNS FROM teams LIKE 'league'";
							$divs = $db->query($sql)->fetchAll();
							$div = $divs[0]['Type'];
														
							$regex = "/'(.*?)'/";
							preg_match_all($regex, $div, $enum_array);
							$enum_fields = $enum_array[1];
							
							foreach($enum_fields as $type) {
								
								if($type == $team['league']) {
									
									print '<option value="' . $team['league'] . '" selected>' . $team['league'] . '</option>';	
									
								}else{
									
									print '<option value="' . $type . '">' . $type . '</option>';
									
								}
							
							} 
						
						?>
                    </select>
                </p>
                <input type="hidden" name="MAX_FILE_SIZE" id="max_file_size" value="300000" />
                <p><label for="team_logo">Team Logo:</label><input type="file" name="team_logo" id="team_logo" /></p>
                <p><label for="url">Team URL:</label><input type="url" name="url" id="url" placeholder="http://www.example.com" value="<?php echo $team['url']; ?>" /></p>
                <input type="submit" name="editTeam" id="editTeam" value="Edit Team" />
                <input type="reset" name="cancel" id="cancel" value="Cancel" />
            </fieldset>
        </form>
    </section>
    <?php require_once 'include/footer.html'; ?>
</body>
</html>